<template>
  <view class="content">
    <view class='ward' v-show="ward"></view>
    <view style='width: 100%;height: 150rpx;background-color: #1976d2;'></view>
    <view class="content-view" style='height:560rpx;margin-top: -100rpx;'>
      <image class="bg-img" src="../../static/orderDetailsBgimg.png"></image>
      <view style='position: absolute;width: 100%;top:0px;padding:42rpx;'>
        <view style='float: left;width: 100%;'>
          <text
            style='float: left;width: 100%;font-weight:bold;font-size: 36rpx;padding: 5px;margin-bottom: 29rpx;color:#3a3a3a'>{{detail.statusDesc}}</text>
          <text class='charge-time' style='color:#fff;background-color: #4ea7ff;'>{{hour}}</text>
          <text class='charge-time'>小时</text>
          <text class='charge-time' style='color:#fff;background-color: #4ea7ff;'>{{min}}</text>
          <text class='charge-time'>分钟</text>
          <text class='charge-time' style='color:#fff;background-color: #4ea7ff;'>{{second}}</text>
          <text class='charge-time'>秒</text>
        </view>
        <text
          style='float: left;width: 100%;margin-top: 40rpx;font-size: 26rpx;color:#858585'>订单日期：{{detail.createTime || ''}}</text>
        <text
          style='float: left;width: 100%;margin-top: 21rpx;font-size: 26rpx;color:#858585'>订单编号：{{detail.code || ''}}</text>
        <text
          style='float: left;width: 100%;margin-top: 21rpx;font-size: 26rpx;color:#858585'>支付信息：{{detail.tradeStateDesc || ''}}</text>
        <view>
          <text style='float: left;margin: 32rpx 0 20rpx;font-size: 34rpx'>{{detail.name || ''}}</text>
          <image v-if="detail.signalIntensity" style="width: 30rpx; height: 30rpx;margin: 40rpx 0 0 12rpx;"
            :src="signalData[detail.signalIntensity]"></image>
          <image v-else style="width: 30rpx; height: 30rpx;margin: 40rpx 0 0 12rpx;" src="/static/offLine.png"></image>
        </view>
        <text style='float: left;width: 100%;font-size: 26rpx;color:#858585'>设备编号：{{detail.cabinetCode || ''}}</text>
      </view>
    </view>

    <view class="content-view" style='margin-top: 5px;'>
      <uni-card>
        <view class="chargedetail">
          <view>
            开始时间：{{detail.startTime || '00:00:00'}}
          </view>
          <view>
            结束时间：{{detail.endTime || '00:00:00'}}</view>
          <view>实时功率：{{detail.power || '0.00'}}W
          </view>

          <view v-if="detail.chargeType == 'QUANTITY'">
            已充电量：{{detail.chargingPower || '0.00'}}kW·h</view>
        </view>
      </uni-card>
      <!-- 订单详情 S -->
      <uni-card :border="false">
        <view class="card2">
          <view class="ordercost">
            <text class="ordercost-title">订单费用</text>
            <view class="more" @click="billingRules" v-if="detail.isCharge !== 1">
              <text>收费组成（电费+服务费+占仓费）</text>
              <image class="more-icon" src="../../static/more.png" mode=""></image>
            </view>
          </view>
          <view class="chargecost">
            <view class="charge">
              <text>是否收费：</text>
            </view>
            <view class="cost">
              <text>{{detail.isCharge === 1 ? '免费' :'收费'}}</text>
            </view>
          </view>
          <view class="chargecost">
            <view class="charge">
              <text>充电类型：</text>
            </view>
            <view class="cost">
              <text v-if="detail.chargeType == 'QUANTITY'">按电量</text>
              <text v-else>按时</text>
            </view>
          </view>
          <view class="chargecost">
            <view class="charge">
              <text>占仓费：</text>
            </view>
            <view class="cost">
              <text>{{detail.billDetailVO.occupyCabinetFees || 0}}元</text>
            </view>
          </view>
          <view class="chargecost" v-if="detail.billDetailVO.serviceFees !=null">
            <view class="charge">
              <text>服务费：</text>
            </view>
            <view class="cost">
              <text>{{detail.billDetailVO.serviceFees}}元</text>
            </view>
          </view>
          <view class="chargecost">
            <view class="charge">
              <text>充电费用：</text>
              <!-- {{`${detail.powerFees}元`}} -->
              <!-- <text v-if="detail.chargeType=='DURATION' || detail.chargeType=='按时'">/{{detail.priceUnit}}小时)</text>
              <text v-else>/kW·h 服务费：{{detail.priceUnit}}/kW·h</text> -->
            </view>
            <view class="cost">
              <text>{{detail.billDetailVO.powerFees || '0.00'}}元</text>
              <!-- <text>{{detail.statusDesc}}</text> -->
            </view>
          </view>
          <view class="total">
            合计：{{detail.billDetailVO.totalBill || '0.00'}}元
          </view>
        </view>

        <view class="bottom-button">
          <!-- status == -1 订单取消；0 预付待确认 1 订单确认 5 发起充电失败 10 发起充电成功
          11 充电中 12 充电暂停 13 充电结束 22 结算完成 25 订单结算完成 30 订单完结-->
          <!-- 取消订单：0，1，5，10
          发起充电：1
          停止充电：11，12
          开仓取出：11，12，13，22 -->
          <button v-if="detail.status == 11 || detail.status ==12" type="default" @click="endModal(detail,'takeout',0)"
            :class="detail.businessState<4?'open':'opens'">停止充电</button>
          <button v-if="detail.status ==11 || detail.status ==12 || detail.status ==13 || detail.status ==22"
            type="default" @click="endModal(detail,'takeout',1)"
            :class="detail.businessState<4?'open':'opens'">开仓取出</button>

          <button type="default"
            v-if="detail.status == 0 || detail.status == 1 || detail.status == 5 || detail.status == 10"
            @click="resultPop()" :class="detail.businessState<4?'open':'opens'">取消订单</button>
          <button v-if="detail.status == 1" type="default" @click="endModal(detail,'takeCharge')"
            :class="detail.businessState<4?'open':'opens'">发起充电</button>
          <button class="opens" v-if="detail.status == 0" type="primary" @click="goPay(detail)">去支付</button>
        </view>
      </uni-card>
      <!-- 订单详情 E -->
    </view>

    <!-- <text v-show="bottonShow" @click="endCharge" class='immobilization-button'>{{bottonName}}</text> -->

    <uni-popup ref="resultpop" type="center" :mask-click="true" :animation="false">
      <view class="result_box">
        <!-- <view class="checks" @click="checkSwitch">
          <uni-data-checkbox v-model="value" :localdata="range" selectedColor='#4ea7ff' :multiple="true"
            @change="checkcChange"></uni-data-checkbox>
          <text>是否放入电池</text>
        </view> -->
        <view class="checks">
          是否取消订单？
        </view>
        <view class="result_btn">
          <button type="default" class="reset" @click="closeResult">取消</button>
          <button type="default" @click="endCharge">确认</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>
<script src='../../config/lodash.js'></script>
<script>
  import {
    showtime
  } from '../../api/showTime.js';
  import moment from '../../components/moment.js';
  import {
    getEnumerate
  } from '../../components/calculate/calculate.js';

  import {
    createOrder,
    charging
  } from '@/api/equip.js';

  import payjs from '@/pages/my/pay.js';

  export default {
    mixins: [payjs],
    data() {
      return {
        hour: '00',
        min: '00',
        second: '00',
        startTime: '',
        endTime: '',
        cabinet: '',
        cabinetCode: '',
        signal: '',
        name: '',
        state: '准备充电',
        code: '',
        date: '',
        dateDifference: '',
        bottonName: '开仓',
        businessState: 2,
        // orderCode: '19b44dea-6e10-11ec-97a4-fefcfe8c111b',
        orderCode: '',
        businessMap: '',
        ward: false,
        responseTime: '',
        bottonShow: true,
        // 是否是订单进来
        status: '',
        info: '',
        total: '',
        costTemplateId: '',
        time: '',
        signalIntensity: '',
        entTime: '',
        createOrderTime: '',
        userPayId: '',
        tradeNo: '',
        overtime: 5,
        cabinetId: '',
        cabinetBinId: '',
        userChargingId: '',
        occupyFees: '',
        loadingShow: {
          OpenGate: true,
          StartCharging: true,
          StopCharging: true,
          Finish: true
        },

        orderId: '', //订单id
        detail: {}, //订单详情信息
        orderStatus: '', //订单状态
        timer: null, //倒计时
        ptimer: null, //充电信息更新

        signalData: {
          1: "/static/1.png",
          2: "/static/2.png",
          3: "/static/3.png",
          4: "/static/4.png",
          5: "/static/5.png",
        },
        createTime:"",
      }
    },
    onLoad(options) {
      this.orderId = options.orderId;
      this.createTime =options.createTime;
      this.orderStatus = options.orderStatus;
      this.getDetail();
      // this.startTime = res.data.beginTime ? moment(res.data.beginTime).format('HH:mm:ss') : '';
    },
    created() {
      this.ptimer = setInterval(() => {
        this.getDetail();
      }, 10 * 1000)
    },
    onHide() {
      if (this.timer) clearInterval(this.timer);
      if (this.ptimer) clearInterval(this.ptimer);
    },
    methods: {
      getDetail() {
        createOrder('/selectOrderDetail', 'get', {
          orderId: this.orderId,
          createTime:this.createTime
        }).then(res => {
          let datas = res.data;
          this.detail = datas;
          // chargingSecond 已充电时长
          let dateTime = this.getTime(Number(datas.chargingSecond));
          this.hour = dateTime[0];
          this.min = dateTime[1];
          this.second = dateTime[2];
          // if (datas.status == 11) { //充电中
          //   let interval = this.countDown(this.detail.startTime);
          //   this.hour = interval.hour;
          //   this.min = interval.minute;
          //   this.second = interval.second;
          //   this.timer = setInterval(() => {
          //     let interval = this.countDown(this.detail.startTime);
          //     this.hour = interval.hour;
          //     this.min = interval.minute;
          //     this.second = interval.second;
          //   }, 1000)
          // } else if ((datas.status == 12 || datas.status == 13 || datas.status == 22 || datas.status == 25 || datas
          //   .status == 30) && datas.endTime) {
          //   // status == -1 订单取消；0 预付待确认 1 订单确认 5 发起充电失败 10 发起充电成功
          //   // 11 充电中 12 充电暂停 13 充电结束 22 结算完成 25 订单结算完成 30 订单完结
          //   if (this.timer) clearInterval(this.timer);
          //   let times = this.countDown(this.detail.startTime, this.detail.endTime);
          //   this.hour = times.hour;
          //   this.min = times.minute;
          //   this.second = times.second;
          // }
        }).catch(error => {
          uni.hideLoading();
        })
      },
      getTime(time) {
        if(!time) return ['00','00','00'];
        // 转换为时分秒
        let h = parseInt(time / 60 / 60 )
        h = h < 10 ? '0' + h : h
        let m = parseInt(time / 60 % 60)
        m = m < 10 ? '0' + m : m
        let s = parseInt(time % 60)
        s = s < 10 ? '0' + s : s
        // 作为返回值返回
        return [h, m, s]
    },


      // 结束订单弹框
      resultPop() {
        this.$refs.resultpop.open();
      },
      // 关闭结束订单弹框
      closeResult() {
        this.$refs.resultpop.close();
      },
      // 去支付
      goPay(item) {
        this.$Toast.loading('支付发起中...');
        charging('/order/pre/pay', 'get', {
          orderId: item.id
        }).then(res => {
          let wechatinfo = res.data;
          this.wechatPay(wechatinfo).then(succ => {}).catch(err => {
            if (err.errMsg == 'requestPayment:ok') { //支付成功
              this.$Toast.success('支付成功');
              setTimeout(() => {
                this.getDetail();
              }, 1500)
            } else if (err.errMsg == 'requestPayment:fail cancel') { //用户取消
              this.$Toast.error('取消支付');
            } else {
              this.$Toast.error('支付失败');
            }
          });
        })
      },
      // 结束充电按钮
      endModal(item, msg, type) {
        let cont = "";
        if (msg == 'takeout' && type == 1) { //开仓取出
          cont = '感谢您的使用，取出电池后请关好仓门。';
        } else if (msg == 'takeout' && type == 0) { //结束充电
          cont = '确定要结束充电吗？';
        } else if (msg == 'takeCharge') { //发起充电
          cont = '确定要发起充电吗？';
        }
        uni.showModal({
          title: '提示',
          content: cont,
          success: (modalRes) => {
            if (modalRes.confirm) {
              if (msg == 'takeout') {
                this.takeout(item, type);
              } else if (msg == 'takeCharge') {
                this.takeCharge(item);
              }
            } else if (modalRes.cancel) {

            }
          }
        })
      },
      // 开仓取出
      takeout(item, type) {
        let url = type == 1 ? '/open/door/get/battery' : '/stop/charging';
        let toast = type == 1 ? '正在开仓···' : '停止充电中···';
        let msg = type == 1 ? '开仓成功' : '充电已结束';
        this.$Toast.loading(toast);
        createOrder(url, 'get', {
            orderId: item.id
          }).then(res => {
            if (res.code == 200) {
              if (type == 1) {
                if (res.data.needPay) { //需要支付
                  uni.hideLoading();
                  let wechatinfo = res.data.wxPrePayVO;
                  this.wechatPay(wechatinfo).then(succ => {}).catch(err => {
                    if (err.errMsg == 'requestPayment:ok') { //支付成功
                      this.getDetail();
                    } else if (err.errMsg == 'requestPayment:fail cancel') { //用户取消
                      this.$Toast.error('取消支付');
                    } else {
                      this.$Toast.error('支付失败');
                    }
                  });
                } else {
                  this.$Toast.success(msg);
                  setTimeout(() => {
                    this.getDetail();
                  }, 1500)
                }
              } else {
                this.$Toast.success(msg);
                setTimeout(() => {
                  this.getDetail();
                }, 1500)
              }
            }
          })
          .catch(err => {

          })
      },
      // 结束订单
      endCharge() {
        this.$Toast.loading('订单取消中');
        createOrder('/charging/finish', 'get', {
          orderId: this.detail.id,
          flag: 0
        }).then(res => {
          this.$refs.resultpop.close();
          if (res.code == 200) {
            this.$Toast.success('订单已取消');
            setTimeout(() => {
              this.getDetail();
            }, 1500)
          }
        }).catch(err => {
          this.$refs.resultpop.close();
        })
      },
      // 发起充电
      takeCharge(item) {
        createOrder('/charging/again', 'get', {
          orderId: item.id
        }).then(res => {
          if (res.code == 200) {
            this.$Toast.success('发起充电指令成功');
            setTimeout(() => {
              this.getDetail();
            }, 1500)
          }
        })
      },

      // 订单详情跳转计费规则
      billingRules() {
        uni.navigateTo({
          url: '../billingRules/billingRules?chargeTmplPriceId=' + this.detail.chargeTmplPriceId
        })
      },
    },

    onHide() {
      if (this.timer) clearInterval(this.timer);
      if (this.ptimer) clearInterval(this.ptimer);
    },
    onUnload() {
      if (this.timer) clearInterval(this.timer);
      if (this.ptimer) clearInterval(this.ptimer);
    },
    finish() {
      if (this.timer) clearInterval(this.timer);
      if (this.ptimer) clearInterval(this.ptimer);
    }
  }
</script>

<style lang="scss" scoped>
  @import url('../commonStyle/commonStyle.css');
  @import "@/static/css/common.scss";

  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-bottom: 100rpx;
  }

  .content-view {
    margin: 0px 10px
  }

  .chargedetail {
    line-height: 62rpx;
    font-size: 28rpx;
    color: #3a3a3a;
    padding: 20rpx 10rpx;
  }

  .bg-img {
    width: 100%;
    position: relative;
    border-radius: 15px;
    height: 100%
  }

  .charge-time {
    float: left;
    width: 93rpx;
    height: 83rpx;
    text-align: center;
    line-height: 83rpx;
    color: #169bd5;
    border-radius: 5px;
  }

  .ward {
    width: 100%;
    height: 100vh;
    background: #9e9e9e99;
    position: fixed;
    z-index: 9998;
    top: 0px;
    bottom: 0px;
  }

  // 订单详情 S
  .card2 {
    padding: 20upx 0;

    .ordercost {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .ordercost-title {
        font-size: 30upx;
        color: #393939;
        font-weight: bold;
      }

      .more {
        display: flex;
        align-items: center;
        font-size: 26upx;
        color: #858585;
      }

      .more-icon {
        width: 10upx;
        height: 17upx;
        margin-left: 10upx;
      }
    }

    .chargecost {
      min-height: 90upx;
      background-color: #f7f7f7;
      padding: 5upx 20upx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20upx;

      .charge {
        font-size: 26upx;
        display: flex;
        align-items: center;

        text {
          color: #3a3a3a;
        }

        view {
          font-size: 24upx;
          color: #858585;
          width: 260upx;
        }
      }

      .cost {
        text:nth-child(1) {
          font-size: 30upx;
          color: #3a3a3a;
          margin-right: 30upx;
        }

        text:nth-child(2) {
          font-size: 24upx;
          color: #3a3a3a;
        }
      }
    }

    .total {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      font-size: 30rpx;
      color: #ff9000;
      font-weight: bold;
      margin-top: 40rpx;
    }
  }

  // 订单详情 E
  .bottom-button {
    @include flexLayout(center, flex-end);

    .open {
      width: 253upx;
      height: 70rpx;
      color: #fff;
      background-color: #c2c2c2;
      line-height: 70rpx;
      font-size: 24rpx;
    }

    .opens {
      width: 210rpx;
      height: 72rpx;
      line-height: 72rpx;
      color: #fff;
      background-color: #4ea7ff;
      font-size: 24rpx;
      margin: 30rpx 10rpx;
    }
  }

  .result_box {
    width: 90%;
    height: 260rpx;
    background: #FFFFFF;
    border-radius: 24rpx;
    padding: 40rpx 60rpx;
    text-align: center;
    font-size: 36rpx;

    .checks {
      @include flexLayout(center, center);
      margin-top: 40rpx;
    }

    text {
      margin-left: -40rpx;
    }

    .result_btn {
      margin-top: 100rpx;
      @include flexLayout(center, space-between);

      button {
        width: 200rpx;
        height: 70rpx;
        line-height: 70rpx;
        margin: 0;
        background: #4ea7ff;
        color: #FFFFFF;
        font-size: 28rpx;
      }

      .reset {
        background: #D8D8D8;
      }
    }
  }

  button::after {
    border: none;
  }
</style>
